package com.txz.system.controller;

import com.txz.common.core.domain.R;
import com.txz.common.core.domain.model.LoginUser;
import com.txz.framework.utils.auth.AuthCommonUtil;
import com.txz.framework.utils.auth.WxAuthUtil; // 微信工具类路径（后续提供）
import com.txz.system.domain.AppUser;
import com.txz.system.service.IAppUserService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 商城登录控制器（支持账号密码登录和微信登录）
 */
@RestController
@RequestMapping("/api/app")
public class AppLoginController {

    @Resource
    private IAppUserService appUserService;

    // 注入新路径的工具类
    @Resource
    private AuthCommonUtil authCommonUtil;

    @Resource
    private WxAuthUtil wxAuthUtil;

    // 账号密码登录（方法实现不变，引用工具类的地方自动适配新路径）
    @PostMapping("/login")
    public R<Map<String, Object>> accountLogin(@RequestBody Map<String, String> loginParam) {
        String username = loginParam.get("username");
        String password = loginParam.get("password");

        AppUser appUser = appUserService.selectAppUserByUsername(username);
        if (appUser == null) {
            return R.fail("用户名不存在");
        }

        // 调用新路径工具类的校验方法
        boolean passwordMatch = authCommonUtil.verifyPassword(password, appUser.getPassword());
        if (!passwordMatch) {
            return R.fail("密码错误");
        }

        LoginUser loginUser = appUserService.buildLoginUser(appUser);
        // 调用新路径工具类的Token生成方法
        String token = authCommonUtil.generateToken(loginUser);

        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        result.put("user", appUser);
        return R.ok(result);
    }

    // 微信授权登录（方法实现不变）
    @PostMapping("/wx/login")
    public R<Map<String, Object>> wxLogin(@RequestBody Map<String, String> param) {
        String code = param.get("code");
        if (code == null || code.isEmpty()) {
            return R.fail("code不能为空");
        }

        try {
            Map<String, String> wxResult = wxAuthUtil.getWxSession(code);
            String openid = wxResult.get("openid");
            String unionid = wxResult.get("unionid");

            AppUser appUser = appUserService.selectAppUserByOpenid(openid);
            if (appUser == null) {
                appUser = appUserService.createWxUser(openid, unionid, "微信用户", "");
            }

            LoginUser loginUser = appUserService.buildLoginUser(appUser);
            String token = authCommonUtil.generateToken(loginUser);

            Map<String, Object> result = new HashMap<>();
            result.put("token", token);
            result.put("user", appUser);
            return R.ok(result);
        } catch (Exception e) {
            return R.fail("微信登录失败：" + e.getMessage());
        }
    }

    // 注册接口（方法实现不变）
    @PostMapping("/register")
    public R<Boolean> register(@RequestBody AppUser appUser) {
        if (appUserService.selectAppUserByUsername(appUser.getUsername()) != null) {
            return R.fail("用户名已存在");
        }
        boolean success = appUserService.register(appUser);
        return success ? R.ok(true) : R.fail("注册失败");
    }
}